#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include<string.h>
#include<memory>
#include "Comm.hpp"

const static int defaultsize = 1024;

class Udpserver
{
public:
    Udpserver(std::string ip, uint16_t port)
        : _ip(ip), _port(port)
    {
    }
    void Init()
    {
        // 创建sockfd,bind
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cout << "socket创建失败！" << std::endl;
            exit(Socket_ERROR);
        }
        std::cout << "socket创建成功！" << std::endl;

        // 补充信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        std::cout<<_port<<std::endl;
        std::cout<<local.sin_port<<std::endl;
        // bind
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            std::cout << "bind失败！" << std::endl;
            exit(Bind_ERROR);
        }
        std::cout << "bind成功！" << std::endl;
    }
    void Start()
    {
        char buffer[defaultsize];
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                buffer[n] = 0;
                std::cout<<"xxxxx@: "<<buffer<<std::endl;
                sendto(_sockfd,buffer,strlen(buffer),0,(struct sockaddr*)&peer,len);
            }
        }
    }
    ~Udpserver(){}
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};